package com.zll.onlineExam.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @name BitmapUtil
 * @date 2022/3/14 17:23
 */
public class BitmapUtil {
    public static String BitmapToBase64(Bitmap bitmap){
        String result = "";
        ByteArrayOutputStream baos = null;
        try{
            if (bitmap != null){
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                baos.flush();
                baos.close();

                byte[] bytes = baos.toByteArray();
                result = Base64.encodeToString(bytes,Base64.NO_WRAP);

            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (baos != null){
                    baos.flush();
                    baos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return "data:image/jpeg;base64,"+result;
    }

    public static Bitmap Base64ToBitmap(String str){
        byte[] bytes = Base64.decode(str, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes,0, bytes.length);

    }

    public static Bitmap cropBitmap(Bitmap bitmap, float maxWidth, float maxHeight){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width > maxWidth || height > maxHeight){
            // 缩放
            Matrix m = new Matrix();
            m.postScale(maxWidth/width,maxHeight/height);
            return Bitmap.createBitmap(bitmap,0,0,width,height,m,false);
        }
        return bitmap;
    }
}
